package com.sky.service.admin.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.admin.DishFlavorMapper;
import com.sky.mapper.admin.DishMapper;
import com.sky.mapper.admin.SetmealDishMapper;
import com.sky.pojo.Dish;
import com.sky.pojo.DishFlavor;
import com.sky.result.PageResult;
import com.sky.service.admin.DishService;
import com.sky.vo.DishVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class DishServiceImpl implements DishService {
    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private DishFlavorMapper dishFlavorMapper;
    @Autowired
    private SetmealDishMapper setmealDishMapper;
    @Override
    public void save(DishDTO dto) throws CloneNotSupportedException {
        Dish dish = dto.clone();
        dishMapper.save(dish);
        dto.getFlavors().forEach(dishFlavor -> dishFlavor.setDishId(dish.getId()));
        dishFlavorMapper.save(dto.getFlavors());

    }

    @Override
    public PageResult pageFind(DishPageQueryDTO dto) {
        PageHelper.startPage(dto.getPage(), dto.getPageSize());
        Page<DishVO> page =  dishMapper.pageFind(dto);
        PageResult pageResult= new PageResult(page.getTotal(),page.getResult());
        return pageResult;
    }

    @Override
    public void delete(List<Integer> ids) {
       Integer count =  dishMapper.selectByIdAndStatus(ids);
        if (count>0){
            throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
        }
        Integer count2= setmealDishMapper.selectByDishId(ids);
        if (count2>0){
            throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }
        dishMapper.delete(ids);

        dishFlavorMapper.delete(ids);

    }

    @Override
    public DishVO selectById(Integer dishId) {

       return dishMapper.selectById(dishId);
    }

    @Override
    public DishVO put(DishDTO dto) {
        DishVO vo = new DishVO();
        BeanUtils.copyProperties(dto,vo);
        dishMapper.put(vo);
        dishFlavorMapper.deleteByDishId(vo.getId());
        List<DishFlavor> flavors = vo.getFlavors();
        flavors.forEach(dishFlavor -> dishFlavor.setDishId(vo.getId()));
        dishFlavorMapper.save(flavors);

        return vo;
    }
}
